package org.kingtop.model;

import com.alibaba.fastjson.serializer.PropertyFilter;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 进行json的序列化字段过滤
 *
 * @author 陈金波
 * @date 2018/1/29 21;55
 */
public class TargetStrategy implements PropertyFilter {
    private static Logger log = LoggerFactory.getLogger(TargetStrategy.class);
    private Class<?> target;
    private String[] fields;
    /**
     * true则setFields设置为返回字段，fasle则setFields设置为过滤字段,默认false
     */
    private boolean reverse = false;

    public TargetStrategy(Class<?> target) {
        super();
        this.target = target;
    }

    @Override
    public boolean apply(Object source, String name, Object value) {
        //是否移除，不序列化
        boolean isSkip = false;
        if (source != null) {
            Class<?> owner = source.getClass();
            // isAssignableFrom 用于判断target是否为owner的父类
            boolean eq = source.getClass().equals(target) || target.isAssignableFrom(owner) || owner.isAssignableFrom(target);
            if (eq) {
                if (ArrayUtils.contains(fields, name)) {
                    log.debug("fitler field:{} for class:{}", owner, owner);
                    isSkip = true;
                }
            }
        }
        return reverse ? isSkip : !isSkip;
    }

    /**
     * 设置字段
     *
     * @param fields
     */
    public void setFields(String[] fields) {
        this.fields = fields;
    }

    /**
     * @param reverse true则setFields设置为返回字段，fasle则setFields设置为过滤字段,默认false
     */
    public void setReverse(boolean reverse) {
        this.reverse = reverse;
    }
}
